package com.kinglumi.ailighting.auth.api;

import com.kinglumi.ailighting.auth.base.BaseController;
import com.kinglumi.ailighting.auth.base.Query;
import com.kinglumi.ailighting.auth.bo.ApiResult;
import com.kinglumi.ailighting.auth.entity.FileInfo;
import com.kinglumi.ailighting.auth.model.FileResponse;
import com.kinglumi.ailighting.auth.service.biz.FileInfoService;
import com.kinglumi.ailighting.auth.service.auth.FileSystemStorageService;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.codec.Utf8;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Lxin
 * @version 1.0
 * @date 2021/8/19 14:48
 */
@RestController
@Slf4j
@RequestMapping("/api/file")
public class FileController extends BaseController<FileInfoService, FileInfo> {

    @Autowired
    FileSystemStorageService fileSystemStorageService;
    @Autowired
    FileInfoService fileInfoService;

    @PostMapping("/uploadFile")
    public ResponseEntity<FileResponse> uploadSingleFile (@RequestParam("file") MultipartFile file, HttpServletRequest request) {

        String upFile = fileSystemStorageService.saveFile(file,request);

        String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath()
                .path("/api/download/")
                .path(upFile)
                .toUriString();

        return ResponseEntity.status(HttpStatus.OK).body(new FileResponse("200","File uploaded with success!",upFile,fileDownloadUri,true,false));
    }

//    @PostMapping("/uploadFiles")
//    public ResponseEntity<List<FileResponse>> uploadMultipleFiles (@RequestParam("files") MultipartFile[] files) {
//
//        List<FileResponse> responses = Arrays.asList(files)
//                .stream()
//                .map(
//                        file -> {
//                            String upfile = fileSytemStorageService.saveFile(file);
//                            String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath()
//                                    .path("/api/download/")
//                                    .path(upfile)
//                                    .toUriString();
//                            return new FileResponse(upfile,fileDownloadUri,"File uploaded with success!");
//                        }
//                )
//                .collect(Collectors.toList());
//
//        return ResponseEntity.status(HttpStatus.OK).body(responses);
//    }


    @GetMapping("/download/{id}")
    public ResponseEntity<Resource> downloadFile(@PathVariable int id) {

        Resource resource = fileSystemStorageService.loadFile(id);

        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + resource.getFilename())
                .body(resource);
    }

    @GetMapping("/download/nowApp")
    public ResponseEntity<Resource> downloadNowApp(Integer scope) throws UnsupportedEncodingException {
        Resource resource = fileSystemStorageService.loadNowApp(scope);
        return ResponseEntity.ok()
                .contentType(MediaType.valueOf(MediaType.MULTIPART_FORM_DATA_VALUE))
//                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + resource.getFilename())
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename="+new String(resource.getFilename().getBytes(), "ISO-8859-1"))
                .body(resource);
    }

    @GetMapping("/nowApp")
    @ResponseBody
    public ApiResult nowApp(Integer scope) {
        FileInfo fileInfo = fileSystemStorageService.nowApp(scope);
        return ApiResult.ok(fileInfo);
    }

    /**
     * @Author: wangyinjie
     * @Description: 获取最新的安卓国内国外的安装包
     * @Date: 12:42 2022/12/3
     * @param
     * @return:
     */
    @GetMapping("/all/nowApp")
    @ResponseBody
    public ApiResult allNowApp() {
        List<FileInfo> list = new ArrayList<>();
        FileInfo fileInfo = fileSystemStorageService.nowApp(1);
        FileInfo file = fileSystemStorageService.nowApp(2);
        list.add(fileInfo);
        list.add(file);
        return ApiResult.ok(list);
    }

    /**
     *  删除文件+记录
     * @param id
     * @return
     */
    @RequestMapping(value = {"/delete/{id}"},method = {RequestMethod.DELETE})
    @ResponseBody
    public ApiResult removeDataAndFile(@PathVariable int id){

        Map<String, Object> result = fileSystemStorageService.deleteDataAndFile(id);
        boolean resultBoolean = ((boolean) result.get("result"));

        if (resultBoolean) {
            return ApiResult.ok();
        }else {
            String message = result.get("message").toString();
            message = StringUtils.trimToEmpty(message);
            return ApiResult.error(message);
        }
    }

    @RequestMapping(
            value = {"/latestVersion/{type}"},
            method = {RequestMethod.GET}
    )
    @ResponseBody
    public ApiResult latestVersion(@PathVariable String type) {
        return ApiResult.ok(fileInfoService.latestVersion(type));
    }

    @RequestMapping(
            value = {"/latestVersion/{type}/{scope}"},
            method = {RequestMethod.GET}
    )
    @ResponseBody
    public ApiResult latestAppVersion(@PathVariable String type, @PathVariable Integer scope) {
        if("ios".equals(type) || "android".equals(type)){
            return ApiResult.ok(fileInfoService.latestVersion(type, scope));
        }else{
            return ApiResult.ok(fileInfoService.latestVersionByBluetoothType(type, scope));
        }
    }

    /**
     * 设置当前app版本
     * @param type
     * @param id
     * @return
     */
    @PostMapping("/update/nowApp")
    @ResponseBody
    public ApiResult updateNowApp(String type, Integer id, Integer scope){
        Map<String, Object> params = new HashMap<>();
        params.put("type", type);
        params.put("scope", scope);
        Query query = new Query(params);
        List<FileInfo> fileInfos = this.baseBiz.selectByQuery(query);
        fileInfos.forEach(info -> {
            info.setNowApp(false);
            this.baseBiz.updateSelectiveById(info);
        });
        FileInfo fileInfo = this.baseBiz.selectById(id);
        fileInfo.setNowApp(true);
        this.baseBiz.updateSelectiveById(fileInfo);
        return ApiResult.ok();
    }
}
